package com.lovelyj.trip_by_train.service.serviceImpl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lovelyj.trip_by_train.entity.DailyRemainTicket;
import com.lovelyj.trip_by_train.entity.Ticket;
import com.lovelyj.trip_by_train.mapper.TicketMapper;
import com.lovelyj.trip_by_train.service.DailyRemainTicketService;
import com.lovelyj.trip_by_train.service.TicketService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDate;
import java.time.LocalDateTime;

@Slf4j
@Service
public class TicketServiceImpl extends ServiceImpl<TicketMapper, Ticket>  implements TicketService {

    @Autowired
    private DailyRemainTicketService dailyRemainTicketService;


    @Override
    @Transactional
    public void createTicket(Ticket ticket,Long dailyRemainTicketId){
        Integer seatClass= ticket.getSeatType();

        LocalDateTime startTime = ticket.getStartTime();
        LocalDateTime endTime = ticket.getEndTime();

        log.info("startTime : {}",startTime);
        log.info("endTime : {}",endTime);


        LambdaUpdateWrapper<DailyRemainTicket> updateWrapper=new LambdaUpdateWrapper<>();
        updateWrapper.eq(DailyRemainTicket::getTrainNum,ticket.getTrainNum())
                .le(DailyRemainTicket::getStartTime, endTime)    // 余票开始时间 <= 车票结束时间
                .ge(DailyRemainTicket::getEndTime, startTime)    // 余票结束时间 >= 车票开始时间
                .setSql("remain_class"+seatClass+" = remain_class"+seatClass+" - 1");

        boolean updated = dailyRemainTicketService.update(updateWrapper);
        if (!updated) {
            throw new RuntimeException("余票不足或时间不匹配，更新失败");
        }

        this.save(ticket);

    }


}
